/**
 * axios全局配置
 */
import Qs from 'qs';
import {Toast} from 'vant'
import VueCookies from 'vue-cookies'

export default function(app) {
    let axios = app.$axios;
    // 基本配置
    //axios.defaults.timeout = 10000;
    // axios.defaults.baseURL = 'http://api.xhhg-ip.com';
    axios.defaults.baseURL = 'http://test.api.xhhg-ip.com';
	// axios.defaults.baseURL = 'http://192.168.124.118';
    axios.defaults.headers.common['Authorization'] = "Bearer " + app.store.state.token;
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    //参数序列化
    axios.interceptors.request.use((config) => {
            if (config.method === 'post') {
                config.data = Qs.stringify(config.data)
            }
            return config;
        }, (error) => {
            return Promise.reject(error)
        })
        //响应拦截器
    axios.interceptors.response.use(
        response => {
            if (response.data.code == 401) {
                /*
                 * 如果请求报错是因为token不存在或过期，就重新登录
                 */
                Toast({
                    message: app.store.state.token ? "您需要重新登录" : "您还没有登录"
                });
                app.store.commit('delToken');
                VueCookies.remove('token');
                if(app.route.path.substr(0, 6) === '/admin'){
                    app.redirect('/admin');
                }else{
                    app.redirect('/');
                }
            }
            return response;
        },
        error => {
            return Promise.resolve(error)
        });
}